﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;

namespace ArgusLib.Drawing
{
	public static class ColorExtension
	{
		public static Color FromHSV(double Hue, double Saturation, double Value)
		{
			while (Hue < 0)
				Hue += 360;
			while (Hue > 360)
				Hue -= 360;

			int h = (int)(Hue / 60);
			double f = Hue / 60 - h;
			double p = Value * (1 - Saturation);
			double q = Value * (1 - Saturation * f);
			double t = Value * (1 - Saturation * (1 - f));
			double[] rgb = null;
			if (h == 0 || h == 6)
			{
				rgb = new double[] { Value, t, p };
			}
			else if (h == 1)
			{
				rgb = new double[] { q, Value, p };
			}
			else if (h == 2)
			{
				rgb = new double[] { p, Value, t };
			}
			else if (h == 3)
			{
				rgb = new double[] { p, q, Value };
			}
			else if (h == 4)
			{
				rgb = new double[] { t, p, Value };
			}
			else if (h == 5)
			{
				rgb = new double[] { Value, p, q };
			}
			return Color.FromArgb(255, (byte)(255 * rgb[0]), (byte)(255 * rgb[1]), (byte)(255 * rgb[2]));
		}

		public static Color Blend(Color source, Color destination, BlendMode blendMode)
		{
			if (blendMode == BlendMode.Alpha)
			{
				if (source.A == 255)
					return source;
				float alphaS = source.A / 255f;
				float alphaD = destination.A / 255f;
				float a = alphaD * (1 - alphaS);
				return Color.FromArgb(
					(byte)(255 * (alphaS + a)),
					(byte)(alphaS * source.R + a * destination.R),
					(byte)(alphaS * source.G + a * destination.G),
					(byte)(alphaS * source.B + a * destination.B));
			}
			else if (blendMode == BlendMode.Additive)
			{
				int a = source.A + destination.A;
				int r = source.R + destination.R;
				int g = source.G + destination.G;
				int b = source.B + destination.B;
				return Color.FromArgb(
					(byte)Math.Min(255, a),
					(byte)Math.Min(255, r),
					(byte)Math.Min(255, g),
					(byte)Math.Min(255, b));
			}
			else
			{
				return source;
			}
		}
	}
}
